﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Net;
using System.IO;

    public class FlightSearch
    {
        private List<FlightInfo> departFlights;

        public List<FlightInfo> _DepartFlights
        {
            get { return departFlights; }
            set { departFlights = value; }
        }

        private List<FlightInfo> returnFlights;

        public List<FlightInfo> _ReturnFlights
        {
            get { return returnFlights; }
            set { returnFlights = value; }
        }

        private string flightType;

        public string _FlightType
        {
            get { return flightType; }
            set { flightType = value; }
        }

        public List<FlightInfo> SearchDepartFlight(string html)
        {
            return GetFlightData(html,"//table[@id='bfm_tbl_out']",false);
        }

        private List<FlightInfo> GetFlightData(string html,string tableXPath,bool isreturn)
        {
            List<FlightInfo> result = new List<FlightInfo>();

            //get root node of html file
            HtmlDocument document = new HtmlDocument();
            document.LoadHtml(html);
            HtmlNode rootNode = document.DocumentNode;

            //get base Uri to confirm
            int index = html.IndexOf("function openSecurity (url)");
            int start = html.IndexOf("\"", index);
            int end = html.IndexOf("\"", start + 1);
            string uri = html.Substring(start + 1, end - start - 1);

            //get table of depart flights
            HtmlNode departflight = rootNode.SelectSingleNode(tableXPath);
            if (departflight == null)
            {
                return null;
            }                   

            //get flight info
            HtmlNodeCollection flights = departflight.SelectNodes(".//tbody/tr");

            foreach (HtmlNode flight in flights)
            {
                HtmlNodeCollection infos = flight.SelectNodes("./td");
                if (infos != null)
                {

                    //Create new flight
                    FlightInfo fly = new FlightInfo();
                    fly._Tickets = new List<TicketType>();

                    //Set info
                    fly._BaseUri = uri;

                    //Depart city => chu y keo depCity lay gia tri cua node truoc
                    List<string> depart = GetCity(infos[1]);
                    fly._DepartCity = depart[0];
                    fly._DepartTime = DateTime.Parse(depart[1]);
                    fly._DepartDescription = depart[2];

                    //arrive city
                    List<string> arrive = GetCity(infos[2]);
                    fly._ArriveCity = arrive[0];
                    fly._ArriveTime = DateTime.Parse(arrive[1]);
                    fly._ArriveDescription = arrive[2];

                    //Flight ID
                    HtmlNode flyID = infos[3].SelectSingleNode(".//span[@class='matrix_airline_code']");
                    fly._FlightID = flyID.InnerText;

                    //Stops
                    HtmlNode stops = infos[4].SelectSingleNode(".//div");
                    fly._Stop = stops.InnerText;

                    //Ticket
                    for (int i = 5; i < infos.Count; i++)
                    {
                        if (i == 6 || i == 8)
                            continue;
                        else
                            getTicket(fly._Tickets, infos[i]);

                    }

                    result.Add(fly);
                }
            }
            return result;
        }

        public List<FlightInfo> GetAllReturnFlight(string html)
        {
            return GetFlightData(html, "//table[@id='bfm_tbl_in']",true);
        }

        private List<string> GetCity(HtmlNode info)
        {
            List<string> result = new List<string>();

            HtmlNode depCity = info.SelectSingleNode(".//a");
            result.Add(Normalize(depCity.InnerText));

            depCity = info.SelectSingleNode(".//p");
            result.Add(Normalize(depCity.InnerText));

            depCity = info.SelectSingleNode(".//td");
            result.Add(Normalize(depCity.InnerText));

            return result;
        }

        private void getTicket(List<TicketType> lsttype, HtmlNode typeNode)
        {
            TicketType type = new TicketType();
            
            //get name
            HtmlNode nameNode = typeNode.SelectSingleNode(".//span[@style='display:none']");
            if (nameNode == null)
            {
                type._Status = "Khong co";
                return;
            }
            //get value to confirm info
            HtmlNode val = typeNode.SelectSingleNode(".//input");
            type._Value = val.Attributes["value"].Value;

            //get type of ticket
            string text = nameNode.InnerText;
            int index = text.IndexOf("messageBrandFareLabel");
            int last = text.IndexOf("@", index+22);
            type._Name = text.Substring(index + 22, last - index - 22);

            //get seat remaing (if have)
            HtmlNode seat = typeNode.SelectSingleNode(".//div[@class='matrix_cal_seatsRemaining_text1']");
            if (seat != null)
            {
                type._SeatRemaining = Normalize(seat.InnerText);
            }

            //get total price
            HtmlNode total = typeNode.SelectSingleNode(".//span[@class='step2PricePoints ']/a");
            HtmlNode currency = total.SelectSingleNode("./span");
            total.RemoveChild(currency);
            type._PriceTotal = long.Parse(Normalize(total.InnerText).Trim());
            type._Unit = Normalize(currency.InnerText).Trim();

            //get detail
            HtmlNodeCollection detail = typeNode.SelectNodes(".//tr");
            List<string> values = new List<string>();
            foreach (HtmlNode p in detail)
            {
                HtmlNodeCollection value = p.SelectNodes(".//td");
                HtmlNode temp = value[1].SelectSingleNode(".//span");
                value[1].RemoveChild(temp);
                values.Add(Normalize(value[1].InnerText).Trim());
            }

            type._Basefare = long.Parse(values[0]);
            type._AXperAdult = long.Parse(values[1]);
            type._UEperAdult = long.Parse(values[2]);



            lsttype.Add(type);
        }

        private string Normalize(string value)
        {
            value = value.Replace("\n","");
            value = value.Replace("\t", "");
            value = value.Replace("\r", "");
            value = value.Trim();
            if (48 <= value[0] && value[0] <= 57)
            {
                value = RemoveChar(value, '.');
                value = RemoveChar(value, ',');
            }
            return value.Trim();
        }
       
        private static string RemoveChar(string value,char c)
        {
            int i = value.IndexOf(c);
            while (i >= 0)
            {
                value = value.Remove(i, 1);
                i = value.IndexOf(c);
            }
            return value;
        }

        public void GetAllFlights(string url)
        {
            WebResponse response = GetSearchStream(url);
            Stream r = response.GetResponseStream();

            StreamReader reader = new StreamReader(r);
            string text = reader.ReadToEnd();

            departFlights = this.SearchDepartFlight(text);
            if (flightType == "returntravel")
            {
                _ReturnFlights = this.GetAllReturnFlight(text);
            }
        }

        public static WebResponse GetSearchStream(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.CookieContainer = new CookieContainer();

            WebResponse response = request.GetResponse();
            return response;
        }

        public WebResponse GetCabins(string baseUri, string outCode, string inCode, string direction, string depCity, string depDay, string depMonth, string arrCity, string arrDay, string arrMonth, string ADT)
        {
            //Get Htmlcode
            HttpWebRequest request = WebRequest.Create(new Uri("https://cat.sabresonicweb.com" + baseUri)) as HttpWebRequest;

            request.Method = "POST";
            request.ServicePoint.Expect100Continue = false;
            request.CookieContainer = new CookieContainer();

            string data = "page=nonFlexairRequestMessage_air" +
                            "&action=airItinSelection" +
                            "&actionType=nonFlex" +
                            "&actionPage=" +
                            "&posid=B3QE" +
                            "&language=en" +
                            "&direction="+ direction +
                            "&departCity=" + depCity +
                            "&depDay="+depDay +
                            "&depMonth="+depMonth +
                            "&depTime=0600" +
                            "&departTime=0600" +
                            "&returnCity="+arrCity +
                            "&retDay="+arrDay +
                            "&retMonth="+arrMonth +
                            "&retTime=0600" +
                            "&returnTime=0600" +
                            "&ADT="+ADT +
                            "&ADT_lnform="+ADT +
                            "&OUT_FLIGHTS_SORTING_BY_DATE_TYPE=" +
                            "&IN_FLIGHTS_SORTING_BY_DATE_TYPE=" +
                            "&SHOW_FILTER_RANGE_FLIGHT_WARNING=" +
                            "&SHOW_FILTER_RANGE_OUTBOUND_FLIGHT_WARNING=" +
                            "&SHOW_FILTER_RANGE_INBOUND_FLIGHT_WARNING=" +
                            "&MATRIX_INTELLISELL=true" +
                            "&fareMatrixPrevURL=" +
                            "&out="+outCode+
                            "&in="+inCode;

            byte[] byteArray = Encoding.UTF8.GetBytes(data);

            request.ContentLength = byteArray.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();

            //Test
            dataStream = response.GetResponseStream();


            StreamReader reader = new StreamReader(dataStream);
            string text = reader.ReadToEnd();

            return response;

        }

        public List<string> GetCabinInfo( WebResponse response)
        {
            Stream dataStream = response.GetResponseStream();


            StreamReader reader = new StreamReader(dataStream);
            string text = reader.ReadToEnd();

            //Get list cabins
            List<string> cabins = new List<string>();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(text);
            HtmlNode root = doc.DocumentNode;

            HtmlNodeCollection depart = root.SelectNodes("//div[@class='column four']/p[@class='aircraft']");
            if (depart != null)
            {
                string departCabin = Normalize(depart[0].InnerText);
                cabins.Add(departCabin);
                if (depart.Count == 2)
                {
                    string arrCabin = Normalize(depart[1].InnerText);
                    cabins.Add(arrCabin);
                }
            }

            return cabins;
        }

        public void SubmitPassenger(string baseUri,string prefix, string middleName, string lastName, string mobile_CityCode, string mobile_PhoneNumber, string homeCode, string homeNumber, string email)
        {
            //Get login page
            string url = "https://cat.sabresonicweb.com" + baseUri + "&page=ssw_PAX_Info&action=SSWPAXInfo&hold_purchase=PURCHASE&shoppingCartUniqueIdForAir=shoppingCartUniqueIdForAir1&stateProvince=";
            HttpWebRequest Getrequest = WebRequest.Create(new Uri(url)) as HttpWebRequest;
            //Getrequest.Headers.Add("Cookie", LoginPageCookie);

            Getrequest.Method = "GET";
            HttpWebResponse Getresponse = Getrequest.GetResponse() as HttpWebResponse;
            
            //Test
            StreamReader str = new StreamReader(Getresponse.GetResponseStream());
            string j = str.ReadToEnd();
            

            //Get passenger page
            string pasUrl = "https://cat.sabresonicweb.com" + baseUri;
            HttpWebRequest Postrequest = WebRequest.Create(new Uri(pasUrl)) as HttpWebRequest;
            Postrequest.Method = "POST";
            Postrequest.ServicePoint.Expect100Continue = false;
            //Postrequest.Headers.Add("Cookie", LoginPageCookie);

            string d =  "page=ssw_UserLoginMessage" +
                        "&posid=B3QE" +
                        "&shoppingCartUniqueIdForAir=shoppingCartUniqueIdForAir1" +
                        "&action=Guest" +
                        "&continueAsGuest=1" +
                        "&guest=true" +
                        "&reminderType=" +
                        "&language=en" +
                        "&accountID=" +
                        "&password=" +
                        "&rememberLoginInfo=" +
                        "&hold_purchase=PURCHASE";
            WebResponse response = GetResponse(Postrequest,d);
            //Test
            StreamReader r = new StreamReader(response.GetResponseStream());
            string t = r.ReadToEnd();

            //get payment page
            HttpWebRequest request = WebRequest.Create(new Uri("https://cat.sabresonicweb.com" + baseUri)) as HttpWebRequest;
            //HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;


            request.Method = "POST";
            request.ServicePoint.Expect100Continue = false;

            string data =   "page=ssw_Payment_Info" +
                            "&shoppingCartUniqueIdForAir=shoppingCartUniqueIdForAir1" +
                            "&language=en" +
                            "&partysize=1" +
                            "&firstTitle1="+ prefix +
                            "&paxType1=ADT" +
                            "&paxTypeDesc1=Adult" +
                            "&firstName1=" + middleName +
                            "&lastName1=" + lastName +
                            "&freqflyer1=VN" +
                            "&frequent_flyer_num1=" +
                            "&ADTDay1=" +
                            "&ADTMonth1=" +
                            "&ADTYear1=" +
                            "&docType1=" +
                            "&docIssuedCountry1=" +
                            "&docNumber1=" +
                            "&docNationality1=" +
                            "&docExpirationDay1=" +
                            "&docExpirationMonth1=" +
                            "&docExpirationYear1=" +
                            "&docGender1=" +
                            "&hidDocPax1=false" +
                            "&docDayOfBirth1=" +
                            "&docMonthOfBirth1=" +
                            "&docYearOfBirth1=" +
                            "&mobile_PhoneCtryCode=84" +
                            "&mobile_PhoneCityCode=" + mobile_CityCode +
                            "&mobile_PhoneNumber=" + mobile_PhoneNumber +
                            "&evening_PhoneCtryCode=84" +
                            "&evening_PhoneCityCode="+ homeCode +
                            "&evening_PhoneNumber=" + homeNumber +
                            "&day_PhoneCtryCode=" +
                            "&day_PhoneCityCode=" +
                            "&day_PhoneNumber=" +
                            "&User_Email1=" + email +
                            "&EMAILFLAG=TRUE" +
                            "&Verify_User_Email1="+ email +
                            "&fax_PhoneCtryCode=" +
                            "&fax_PhoneCityCode=" +
                            "&fax_PhoneNumber=" +
                            "&User_Email2=" +
                            "&Verify_User_Email2=" +
                            "&EMAILFLAG2=TRUE" +
                            "&aeClicked=false" +
                            "&action=SSWPaymentInfo";
            WebResponse rs =  GetResponse(request, data);
            //Test
            StreamReader rd = new StreamReader(rs.GetResponseStream());
            string text = rd.ReadToEnd();
        }

        public string GetBookingCode(string baseUri, string totalPrice, string baseFare, string bankName)
        {
            HttpWebRequest request = WebRequest.Create(new Uri("https://cat.sabresonicweb.com" + baseUri)) as HttpWebRequest;
            request.Method = "POST";

            request.ServicePoint.Expect100Continue = false;
            string data =   "page=ssw_Payment_Info" +
                            "&TDS_PHASE=Validate" +
                            "&isCustomCCard=false" +
                            "&shoppingCartUniqueIdForAir=shoppingCartUniqueIdForAir1" +
                            "&language=en" +
                            "&TOTAL_DUE=" + totalPrice +
                            "&TOTAL_CC_DUE=" + totalPrice +
                            "&SEAT_TOTAL=0" +
                            "&SSR_TOTAL=0.0" +
                            "&TOTAL_AIR_TAXES="+ totalPrice +
                            "&CHANGE_FEE=0" +
                            "&OTHER_FEE=0" +
                            "&REFUND_AMT=0" +
                            "&FEE_TAX=0" +
                            "&SEC_FEE_TAX=0" +
                            "&EXCH_CREDIT=0" +
                            "&serverUrl=https=//cat.sabresonicweb.com" +
                            "&TOTAL_CREDIT_BANK=0" +
                            "&TOTAL_BEFORE_CC_SURCHARGE=" + baseFare +".00" +
                            "&TOTAL_BEFORE_INSURANCE=" + totalPrice + ".00" +
                            "&TOTAL_AFTER_CC_SURCHARGE=" + totalPrice + ".00" +
                            "&COMMA_FORMATTING=true" +
                            "&displayPinCC=" +
                            "&ccCode=XX" +
                            "&ccCodeSelectedIndex=" +
                            "&cardNumber=" +
                            "&cardValidFromMonth=" +
                            "&cardValidFromYear=" +
                            "&cardHolderName=" +
                            "&cardExpMonth=1" +
                            "&cardExpYear=2012" +
                            "&cardHolderSecurityCode=" +
                            "&cardHolderPinCode=" +
                            "&cardIssueNumber=" +
                            "&payHow=AGENCY" +
                            "&agCode="+ bankName +
                            "&billingAddress1=" +
                            "&billingAddress2=" +
                            "&billingCity=" +
                            "&billingStateProv=" +
                            "&billingZip=" +
                            "&billingCountry=VN" +
                            "&deliverHow=eticket" +
                            "&deliveryAddress1=" +
                            "&deliveryCity=" +
                            "&deliveryAddress2=" +
                            "&deliveryAddress3=" +
                            "&deliveryAddress4=" +
                            "&deliveryStateProv=" +
                            "&deliveryZip=" +
                            "&deliveryCountry=" +
                            "&farerule1=ELIGIBILITY :   VALID FOR NEG PSGR." +
                            "DAY_TIME :   NO DAY/TIME TRAVEL RESTRICTIONS APPLY." +
                            "SEASONALITY :   NO SEASONAL TRAVEL RESTRICTIONS APPLY." +
                            "FLIGHT_APPLICATION :   NO FLIGHT RESTRICTIONS APPLY." +
                            "ADVANCE_RESERVATIONS_TICKETING :   CONFIRMED RESERVATIONS ARE REQUIRED FOR ALL SECTORS." +
                            "MINIMUM_STAY :   NO MINIMUM STAY REQUIREMENTS APPLY." +
                            "MAXIMUM_STAY :   TRAVEL FROM LAST STOPOVER MUST COMMENCE NO LATER THAN" +
                            "  12 MONTHS AFTER DEPARTURE FROM FARE ORIGIN." +
                            "STOPOVERS :   STOPOVERS ARE NOT PERMITTED AT INTERMEDIATE POINTS." +
                            "TRANSFERS :   NO TRANSFERS PERMITTED." +
                            "  FARE BREAK AND EMBEDDED SURFACE SECTORS NOT PERMITTED" +
                            "  ON THE FARE COMPONENT." +
                            "COMBINATIONS :   END-ON-END" +
                            "  END-ON-END COMBINATIONS PERMITTED. VALIDATE ALL FARE" +
                            "  COMPONENTS. SIDE TRIPS PERMITTED WITH NO" +
                            "  RESTRICTIONS. TRAVEL MUST BE VIA THE POINT OF" +
                            "  COMBINATION." +
                            "  PROVIDED -" +
                            "  COMBINATIONS ARE FOR CARRIER VN IN RULE SW01/SW02" +
                            "  IN TARIFF" +
                            "  TPFDRPV - WITHIN AREA 3-DOMESTIC" +
                            "  OR RULE SW01 IN TARIFF" +
                            "  174ATP" +
                            "  EUASRPV - BETWEEN EUROPE-AREA 3" +
                            "  TPFGRPV - WITHIN AREA 3-INTERNATIONAL" +
                            "  TPPVR   - BETWEEN AREA 1-AREA 2/3 VIA PAC." +
                            "  OPEN JAWS/ROUND TRIPS/CIRCLE TRIPS" +
                            "  FARES MAY BE COMBINED ON A HALF ROUND TRIP BASIS" +
                            "  WITH VN FARES" +
                            "  -TO FORM SINGLE OR DOUBLE OPEN JAWS" +
                            "  -TO FORM ROUND TRIPS" +
                            "  -TO FORM CIRCLE TRIPS WITH VN FARES." +
                            "  PROVIDED -" +
                            "  COMBINATIONS ARE WITH ANY FARE FOR CARRIER VN IN" +
                            "  RULE SW01/SW02 IN TARIFF" +
                            "  TPFDRPV - WITHIN AREA 3-DOMESTIC" +
                            "  OR RULE SW01 IN TARIFF" +
                            "  174ATP" +
                            "  EUASRPV - BETWEEN EUROPE-AREA 3" +
                            "  TPFGRPV - WITHIN AREA 3-INTERNATIONAL" +
                            "  TPPVR   - BETWEEN AREA 1-AREA 2/3 VIA PAC." +
                            "BLACKOUT_DATES :   ORIGINATING SGN INBOUND -" +
                            "  TRAVEL IS NOT PERMITTED 25JAN12 THROUGH 07FEB12 OR" +
                            "  13FEB13 THROUGH 24FEB13." +
                            "  ORIGINATING SGN OUTBOUND -" +
                            "  TRAVEL IS NOT PERMITTED 07JAN12 THROUGH 26JAN12 OR" +
                            "  31JAN13 THROUGH 11FEB13." +
                            "  ORIGINATING HAN OUTBOUND -" +
                            "  TRAVEL IS NOT PERMITTED 25JAN12 THROUGH 07FEB12 OR" +
                            "  13FEB13 THROUGH 24FEB13." +
                            "  ORIGINATING HAN INBOUND -" +
                            "  TRAVEL IS NOT PERMITTED 07JAN12 THROUGH 26JAN12 OR" +
                            "  31JAN13 THROUGH 11FEB13." +
                            "SURCHARGES :   NO SURCHARGE REQUIREMENTS APPLY." +
                            "ACCOMPANIED_TRAVEL :   ACCOMPANIED TRAVEL NOT REQUIRED." +
                            "TRAVEL_RESTRICTIONS :   VALID FOR TRAVEL COMMENCING ON/AFTER 16OCT12. ALL" +
                            "  TRAVEL MUST BE COMPLETED BY MIDNIGHT ON 31MAR13." +
                            "SALES_RESTRICTIONS :   FARES MAY ONLY BE SOLD BY VN." +
                            "  TICKETS MUST BE ISSUED ON THE STOCK OF VN AND MAY ONLY" +
                            "  BE SOLD BY CRS/CXR DEPT IRU." +
                            "PENALTIES :   CANCELLATIONS" +
                            "" +
                            " ANY TIME" +
                            "  CHARGE VND 300000 FOR REFUND." +
                            "  CHILD/INFANT DISCOUNTS APPLY." +
                            "" +
                            "  CHANGES" +
                            "" +
                            "  CHANGES PERMITTED FOR REVALIDATION." +
                            "  NOTE - TEXT BELOW NOT VALIDATED FOR AUTOPRICING." +
                            "  - REROUTING IS PERMITTED WITH FEE OF VND 300000" +
                            "  - REISSUE/EXCHANGE PERMITTED TO EQUAL OR HIGHER FA" +
                            "  RES ONLY" +
                            "HIP_MILEAGE_EXCEPTIONS :   THE HIGHER INTERMEDIATE POINT RULE DOES NOT APPLY FOR" +
                            "  STOPOVERS" +
                            "  OR - THE HIGHER INTERMEDIATE POINT RULE DOES NOT APPLY" +
                            "  FOR CONNECTIONS." +
                            "TICKET_ENDORSEMENTS :   THE ORIGINAL AND THE REISSUED TICKET MUST BE ANNOTATED" +
                            "  - NON-END. REST MAY APPLY - AND - CONTACT VN OFF B4" +
                            "  FLT DATE - AND - CONTACT VN OFF B4 FLT DATE - IN THE" +
                            "  ENDORSEMENT BOX." +
                            "CHILDREN_DISCOUNTS :   CNN/ACCOMPANIED CHILD PSGR 2-11 - CHARGE 75 PERCENT OF" +
                            "  THE FARE." +
                            "  TICKETING CODE - BASE FARE CODE PLUS CH25." +
                            "  MUST BE ACCOMPANIED ON ALL FLIGHTS IN THE SAME" +
                            "  COMPARTMENT BY ADULT PSGR 12 OR OLDER." +
                            "  OR - 1ST INF/INFANT WITHOUT A SEAT PSGR UNDER 2 -" +
                            "  CHARGE 10 PERCENT OF THE FARE." +
                            "  TICKETING CODE - BASE FARE CODE PLUS IN90." +
                            "  MUST BE ACCOMPANIED ON ALL FLIGHTS IN THE SAME" +
                            "  COMPARTMENT BY ADULT PSGR 12 OR OLDER." +
                            "  CNE/NEGOTIATED CHILD PSGR 2-11 - CHARGE 75 PERCENT OF" +
                            "  THE FARE." +
                            "  TICKETING CODE - BASE FARE CODE PLUS CH25." +
                            "  MUST BE ACCOMPANIED ON ALL FLIGHTS IN THE SAME" +
                            "  COMPARTMENT BY ADULT PSGR 12 OR OLDER." +
                            "  OR - 1ST INE/NEGOTIATED INFANT PSGR UNDER 2 - CHARGE 10" +
                            "  PERCENT OF THE FARE." +
                            "  TICKETING CODE - BASE FARE CODE PLUS IN90." +
                            "  MUST BE ACCOMPANIED ON ALL FLIGHTS IN THE SAME" +
                            "  COMPARTMENT BY ADULT PSGR 12 OR OLDER." +
                            "TOUR_CONDUCTOR_DISCOUNTS :   NO DISCOUNTS FOR TOUR CONDUCTORS." +
                            "AGENT_DISCOUNTS :   NO DISCOUNTS FOR SALE AGENTS." +
                            "ALL_OTHER_DISCOUNTS :   NO DISCOUNTS FOR OTHERS." +
                            "MISCELLANEOUS_PROVISIONS :   NO PROVISIONS APPLY." +
                            "GROUPS :   NO GROUP PROVISIONS APPLY." +
                            "TOURS :   NO TOUR PROVISIONS APPLY." +
                            "VISIT_ANOTHER_COUNTRY :   NO VISIT A" +
                            "            NOTHER COUNTRY PROVISIONS APPLY." +
                            "DEPOSITS :   NO DEPOSIT PROVISIONS APPLY." +
                            "VOLUNTARY_REFUNDS :   CHECK CATEGORY 16 OR CONTACT CARRIER FOR DETAILS." +
                            "RULE_APPLICATION_AND_OTHER_CONDITIONS :   NOTE - THE FOLLOWING TEXT IS INFORMATIONAL AND NOT" +
                            "  VALIDATED FOR AUTOPRICING." +
                            "  VN WEB PROMOTIONAL FARES" +
                            "  APPLICATION" +
                            "  AREA" +
                            "  THESE FARES APPLY AREA 3." +
                            "  TYPES OF TRANSPORTATION" +
                            "  FARES GOVERNED BY THIS RULE CAN BE USED TO CREATE" +
                            "  ONE-WAY/ROUND-TRIP/CIRCLE-TRIP/OPEN-JAW JOURNEYS." +
                            "TERMS_TEXT:Please review our full terms and conditions available through the link below or visit http://www.vietnamairlines.com/wps/portal/en/site/terms" +
                            "" +
                            "You must acknowledge that you have reviewed and accepted these terms and conditions before completing your purchase." +
                            "" +
                            "This section applies specifically to bookings and payments available on this site and made here." +
                            "" +
                            "When using this online facility you agree to all applicable terms, conditions and notices, including but not limited to the Conditions of Use. If this is not your intention and/or you disagree with any part of applicable terms and conditions, do not use this facility and please leave." +
                            "" +
                            "You represent that you are of legal age to use this site and to have legal obligations for any liability you may incur as a result of the use of this online booking facility." +
                            "" +
                            "In addition to the general terms and conditions, but not restricted to, you must acknowledge, agree to and accept the following points:" +
                            "" +
                            "•           You are financially responsible for all uses of this site, by yourself and those using your login information" +
                            "" +
                            "•           You warrant that all information supplied by you and members of your household in using this booking facility is true and accurate" +
                            "" +
                            "•           Change and cancellation fees may apply, details are found in the fare rules" +
                            "" +
                            "•           Baggage allowance can be found in the fare rules and in the general terms and conditions" +
                            "" +
                            "•           If you purchased the ticket(s) by Visa/MasterCard, The card holder must verify card at time of check-in or at Vietnam Airlines Ticketing Offices before travelling" +
                            "" +
                            "•           If you will be paying by Vietnam Domestic Card, the payment transaction code will be shown in your e-ticket receipt(s)" +
                            "" +
                            "•           To change your tickets or itinerary, please contact the nearest Vietnam Airlines Ticketing Offices" +
                            "" +
                            "•           Applicable taxes, fees and charges imposed by government or other authority shall be payable by you. The taxes, fees and charges imposed on air travel can change at any time and can be imposed after your ticket has been issued" +
                            "" +
                            "•           You must not resell the service of the online booking facility, use the online booking facility for any activity which breaches any law or in a way which interferes with its availability for other users, or use other means to transact or obtain information if you unable to use the online booking facility" +
                            "" +
                            "•           If Vietnam Airlines, in its sole discretion, believes that you are in breach, or will be in breach, of any of these restrictions, we reserve the right to cancel your booking without giving you a reason and/or without further reference to you" +
                            "" +
                            "•           Governments may require the carrier to provide information on or permit access to passenger data" +
                            "TERMS_INSURANCE_TEXT: " +
                            "terms:Please review our full terms and conditions available through the link below or visit http://www.vietnamairlines.com/wps/portal/en/site/terms " +
                            "" +
                            "You must acknowledge that you have reviewed and accepted these terms and conditions before completing your purchase." +
                            "" +
                            "This section applies specifically to bookings and payments available on this site and made here." +
                            "" +
                            "When using this online facility you agree to all applicable terms, conditions and notices, including but not limited to the Conditions of Use. If this is not your intention and/or you disagree with any part of applicable terms and conditions, do not use this facility and please leave." +
                            "" +
                            "You represent that you are of legal age to use this site and to have legal obligations for any liability you may incur as a result of the use of this online booking facility." +
                            "" +
                            "In addition to the general terms and conditions, but not restricted to, you must acknowledge, agree to and accept the following points:" +
                            "" +
                            "•           You are financially responsible for all uses of this site, by yourself and those using your login information" +
                            "" +
                            "•           You warrant that all information supplied by you and members of your household in using this booking facility is true and accurate" +
                            "" +
                            "•           Change and cancellation fees may apply, details are found in the fare rules" +
                            "" +
                            "•           Baggage allowance can be found in the fare rules and in the general terms and conditions" +
                            "" +
                            "•           If you purchased the ticket(s) by Visa/MasterCard, The card holder must verify card at time of check-in or at Vietnam Airlines Ticketing Offices before travelling" +
                            "" +
                            "•           If you will be paying by Vietnam Domestic Card, the payment transaction code will be shown in your e-ticket receipt(s)" +
                            "" +
                            "•           To change your tickets or itinerary, please contact the nearest Vietnam Airlines Ticketing Offices" +
                            "" +
                            "•           Applicable taxes, fees and charges imposed by government or other authority shall be payable by you. The taxes, fees and charges imposed on air travel can change at any time and can be imposed after your ticket has been issued" +
                            "" +
                            "•           You must not resell the service of the online booking facility, use the online booking facility for any activity which breaches any law or in a way which interferes with its availability for other users, or use other means to transact or obtain information if you unable to use the online booking facility" +
                            "" +
                            "•           If Vietnam Airlines, in its sole discretion, believes that you are in breach, or will be in breach, of any of these restrictions, we reserve the right to cancel your booking without giving you a reason and/or without further reference to you" +
                            "" +
                            "•           Governments may require the carrier to provide information on or permit access to passenger data" +
                            "&termsConditions=on" +
                            "&action=finalReview" +
                            "&purch_submit=Purchase";

            WebResponse response = GetResponse(request, data);
            StreamReader r = new StreamReader(response.GetResponseStream());
            string html = r.ReadToEnd();

            //Get code
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            HtmlNode root = doc.DocumentNode;

            HtmlNode code = root.SelectSingleNode("//div[@id='pageContent']//div[@class='recordLocaterDescText']//span[@class='recordLocater']");
            string bookingCode = null;
            if (code != null)
            {
                bookingCode = Normalize(code.InnerText);
            }
            return bookingCode;
        }

        private static WebResponse GetResponse(HttpWebRequest request,string data)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(data);

            request.ContentLength = byteArray.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            return response;
        }
    }
